package com.awesome.common.util
import android.app.Activity
import java.util.*

/**
 * Author: JFangZ
 * Email: janezhang1901@163.com
 * Date: 2020/8/26 9:44
 * Description:Activity 管理者
 */
object ActivityManager {
    private val mActivityStack = Stack<Activity>()
    fun addActivity(activity: Activity) {
        mActivityStack.add(activity)
    }

    fun removeActivity(activity: Activity): Boolean {
        return mActivityStack.remove(activity)
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/8/26 10:11
     * Description:获取栈顶 Activity
     */
    fun getTopActivity(): Activity? {
        return if (mActivityStack.isEmpty()) {
            null
        } else {
            mActivityStack.lastElement()
        }
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/12/30 14:10
     * Description:获取栈中指定的 Activity 最靠前的那一个
     */
    fun getTopActivity(clazz: Class<*>): Activity? {
        for (i in mActivityStack.indices.reversed()) {
            if (clazz == mActivityStack.elementAt(i).javaClass) {
                return mActivityStack.elementAt(i)
            }
        }
        return null
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/8/26 9:46
     * Description:退出某个 Activity 上的所有 Activity
     *
     * @param clazz 需要显示到栈顶的 Activity 的 class
     */
    fun exitActivityUntilOne(clazz: Class<*>) {
        while (true) {
            val activity = getTopActivity()
            if (activity == null || activity.javaClass == clazz) {
                break
            }
            if (removeActivity(activity)) {
                activity.finish()
            }
        }
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2020/8/26 9:46
     * Description:退出所有 Activity
     */
    fun exit() {
        while (true) {
            val activity = getTopActivity()
                    ?: break
            if (removeActivity(activity)) {
                activity.finish()
            }
        }
    }
}